<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class mOrder extends Model {

    // 商品售价数组
    private $productSalePrices;
    // 订单商品数量
    private $order_product_count = 0;
    // 发货通知接口
    private $deliver_notify_url = "https://api.weixin.qq.com/pay/delivernotify?access_token=";

    /**
     * Create New Order <wechat payment success>
     * @param string $wepaySerial
     * @param int $orderList
     * @return <boolean>
     * @todo 事务处理
     */
    public function create($openid, $wepaySerial = '', $orderList = array(), $addrData = array(), $balancePay = false, $yun = 0, $leword = '') {
        // order infos
        $orderAmount = $this->sumOrderAmount($orderList) + $yun;
        $companyCom = isset($_COOKIE['com']) ? $_COOKIE['com'] : '0';
        // 如果使用余额支付
        if ($balancePay) {
            $uinfo = $this->User->getUserInfo();
            if ($uinfo->balance >= $orderAmount) {
                $orderBalance = $orderAmount;
            } else {
                $orderBalance = $uinfo->balance;
            }
            // 减余额
            $this->User->mantUserBalance($orderBalance, $uinfo->uid, $type = User::MANT_BALANCE_DIS);
        } else {
            $orderBalance = 0.00;
        }

        // orders
        $SQL_order = sprintf("INSERT INTO `orders` (`company_com`,`product_count`,`order_balance`,`order_amount`,`order_yunfei`,`order_time`,`last_mod`,`wepay_serial`,`wepay_openid`,`leword`) VALUES ('%s', %s, %s, %s, %s, NOW(),NOW(),'%s','%s','%s');", $companyCom, $this->order_product_count, $orderBalance, $orderAmount, $yun, $wepaySerial, $openid, $leword);
        # echo $SQL_order;
        $orderId = $this->Db->query($SQL_order);
        // orders_details
        $SQL_orderDetails = $this->genOrderDetailSQL($orderId, $orderList);
        // finalquery
        $this->Db->query($SQL_orderDetails);
        // 写入订单地址
        return $this->writeAddressData($orderId, $addrData) ? $orderId : false;
    }

    /**
     * 
     * @param type $orderList
     * @return <Int> orderAmount
     */
    private function sumOrderAmount($orderList) {
        $Inquery = array();
        $return = 0;
        foreach ($orderList as $pd => $va) {
            $this->order_product_count += intval($va);
            array_push($Inquery, $pd);
        }
        // product list query
        $SQL = sprintf("SELECT `product_id`,`sale_prices` FROM product_onsale WHERE product_id IN (%s);", implode(' ,', $Inquery));
        $salePricesRes = $this->Db->query($SQL);
        $this->productSalePrices = array();
        foreach ($salePricesRes as $product) {
            // count order total price
            $this->productSalePrices[$product['product_id']] = $product['sale_prices'];
            $return += $product['sale_prices'] * $orderList[$product['product_id']];
        }
        return $return;
    }

    /**
     * 
     * @param type $orderList
     * @return SQLstatment <string>
     */
    private function genOrderDetailSQL($orderId, $orderList) {
        // original sql statment
        $SQL = sprintf("INSERT INTO orders_detail 
            (`order_id`,`product_id`,`product_count`,`product_saleprice`,`product_inprice`,`product_discount_price`,`is_returned`)
            VALUES ");
        $_tmp = array();
        foreach ($orderList as $productId => $productCount) {
            // pack params
            array_push($_tmp, sprintf("(%s, %s, %s, %s, 0, %s, 1)", $orderId, $productId, $productCount, $this->productSalePrices[$productId], $this->productSalePrices[$productId]));
        }
        return $SQL . implode(',', $_tmp) . ';';
    }

    /**
     * 
     * @param type $orderid
     * @param type $addrData
     * @return <boolean>
     */
    public function writeAddressData($orderid, $addrData) {
        //userName 收货人姓名
        //telNumber 收货人电话
        //addressPostalCode 邮编
        //address 详细地址
        $SQL = sprintf("INSERT INTO `" . TABLE_ORDERS_ADDRESS . "` (`order_id`,`user_name`,`tel_number`,`postal_code`,`address`) VALUES ('%s', '%s', '%s', '%s', '%s');", $orderid, $addrData['userName'], $addrData['telNumber'], $addrData['PostalCode'], $addrData['Address']);
        # echo $SQL;
        return $this->Db->query($SQL) >= 0;
    }

    /**
     * despacthGood
     * 发货 - 通知
     */
    public function despacthGood($orderId, $expressCode, $expressCompany) {
        $SQL = sprintf("UPDATE `orders` SET `last_mod` = NOW(),`status` = 'delivering',`express_code` = '%s',`express_com`='%s' WHERE order_id = $orderId;", $expressCode, $expressCompany);
        $AffectRow = $this->Db->query($SQL);
        if ($AffectRow != false) {
            $this->wechat_deliverNotify($orderId);
            return true;
        }
        return false;
    }

    /**
     * 微信后台发货通知接口
     */
    public function wechat_deliverNotify($orderId) {

        include_once(dirname(__FILE__) . "/../lib/Tools.php");
        include_once(dirname(__FILE__) . "/../lib/wepaySdk/WxPayHelper.php");
        include_once(dirname(__FILE__) . "/WechatSdk.php");

        $SignTool = new SignTool();
        $orderId = (string) $orderId;

        $dtime = (string) time();

        $data = $this->Db->query("SELECT `wepay_serial`,`wepay_openid` FROM `orders` WHERE `order_id` = $orderId;");
        $data = $data[0];

        $Stoken = WechatSdk::getServiceAccessToken();

        // app_signature：appid、appkey、openid、transid、out_trade_no、deliver_timestamp、deliver_status、deliver_msg

        $SignTool->setParameter('appid', APPID);
        $SignTool->setParameter('appkey', APPSECRET);
        $SignTool->setParameter('deliver_timestamp', $dtime);
        $SignTool->setParameter('deliver_status', "1");
        $SignTool->setParameter('deliver_msg', "ok");
        $SignTool->setParameter('openid', $data['wepay_openid']);
        $SignTool->setParameter('out_trade_no', $orderId);
        $SignTool->setParameter('transid', $data['wepay_serial']);

        $WxPayHelper = new WxPayHelper();
        $app_signature = $WxPayHelper->get_biz_sign($SignTool->parameters);

        $postData = array(
            "appid" => APPID,
            "openid" => $data['wepay_openid'],
            "transid" => $data['wepay_serial'],
            "out_trade_no" => $orderId,
            "deliver_timestamp" => $dtime,
            "deliver_status" => "1",
            "deliver_msg" => "ok",
            "app_signature" => $app_signature,
            "sign_method" => SIGNTYPE
        );

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $this->deliver_notify_url . $Stoken);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // exec
        curl_exec($curl);
        // close
        curl_close($curl);

        // 微信消息
    }

    /**
     * 管理后台获取订单列表
     * @param type $Query
     */
    public static function wdminGetOrderList($Query) {
        
    }

    /**
     * 获取订单详情
     * @param <int> $id 订单id
     */
    public function wdminGetOrderDetail($id) {
        $id = intval($id);
        $SQL = "SELECT * FROM `orders` WHERE `order_id` = $id";
        $orderData = $this->Db->query($SQL);
        $orderData = $orderData[0];
        $address = $this->Db->query("SELECT * FROM `orders_address` WHERE order_id = $id;");
        $orderData['address'] = $address[0];
        $orderData['products'] = $this->Db->query("SELECT catimg,`pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vproductinfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $orderData['order_id']);
        return $orderData;
    }

    public function test() {
        
    }

}
